<template>
  <view>
    <u-line></u-line>
    <u-index-list :indexList="indexList">
        <view style="padding: 0 30rpx ">
          <view @click="hideLocation" style="padding: 30rpx 0">暂不设置</view>
        </view>
        <u-line></u-line>
        <view style="padding: 0 30rpx ">
          <view style="padding: 30rpx 0;display: flex;align-items: center ">
            <text style="color:rgba(84,87,87,0.5);font-size: 14px">当前位置</text>
            &nbsp;<u-icon color="#30dbf6" name="map"></u-icon></view>
          <text @click="alterLocation" v-if="!locationLoading">{{SignAddress}}</text>
          <u-loading-icon v-else text="加载中" textSize="18"></u-loading-icon>
        </view>
        <u-line></u-line>
        <view style="padding: 0 30rpx 30rpx 30rpx">
          <view style="padding: 30rpx 0;color:rgba(84,87,87,0.5);font-size: 14px">其他地区</view>
          <text @click="toAlterState(country)">{{country}}</text>
        </view>
        <u-line></u-line>
      <u-loading-page v-if="countyLoading" loading-text="loading..."></u-loading-page>
      <template v-else :key="index" v-for="(item, index) in indexList">
        <!-- #ifdef APP-NVUE -->
        <u-index-anchor bg-color="white" :text="indexList[index]"></u-index-anchor>
        <!-- #endif -->
        <u-index-item >
          <!-- #ifndef APP-NVUE -->
          <u-index-anchor bg-color="white" :text="indexList[index]"></u-index-anchor>
          <!-- #endif -->
          <view class="list" @click="toAlterState(item1.country)" v-for="(item1, index1) in indexMap.get(item)" :key="index1">
            <view class="list__item">
              <text class="list__item__user-name">{{ item1.country }}</text>
            </view>
          </view>
        </u-index-item>
      </template>
    </u-index-list>
  </view>
</template>

<script>
import {alterFrontUserLocation, getCountryList, getStateList} from "@/api/user";

const indexList = () => {
  const indexList = []
  const charCodeOfA = 'a'.charCodeAt(0)
  for (let i = 0; i < 26; i++) {
    indexList.push(String.fromCharCode(charCodeOfA + i))
  }
  indexList.push('#')
  return indexList
}
import amap from '@/components/amap-wx.130.js'

export default {
  data() {
    return {
      countyList:[],
      country:'',
      location: {
      },
      locationInfo: {
        province: '',
        city: '',
        district: '',
      },
      locationLoading: true,
      countyLoading: true,
      indexList: indexList(),
      amapPlugin: null,
      key: '1518052a103b8a86a3fb4b69f7eb9c2a', //高德小程序key
      SignAddress: '' , //位置信息
      indexMap:new Map()
    };
  },
  onLoad() {
    this.amapPlugin = new amap.AMapWX({
      key: this.key
    });
    this.getNowPlace() //获取定位方法
    this.getCountryList()
  },
  methods: {
    hideLocation(){
      this.location = {
        country: '',
        province: '',
        city: '',
      }
      this.alterLocation()
    },
    async alterLocation(){
      const res = await alterFrontUserLocation(this.location)
      if(res.code == 200){
        uni.$emit("alterLocation",{success: true})
        setTimeout(()=>{
          uni.navigateBack({
            delta: 1
          })
      },500)
      }else{
        uni.$emit("alterLocation",{success: false})
      }
    },
    toAlterState(country){
      getStateList(country).then(res=>{
        if(res.code == 200){
          console.log(country)
          if((res.data[0]?.state !== undefined)){
            console.log("有state")
            setTimeout(()=>{
              uni.navigateTo({
                url: '/pages/my/alterState?country='+country
              })
            },500)
          } else {
            console.log("无state")
            setTimeout(()=>{
              uni.navigateTo({
                url: '/pages/my/alterCity?country='+country
              })
            },500)
          }
        }
      })

    },
   async getCountryList(){
      const res = await getCountryList()
     this.countyList = res.data
     this.country = this.countyList[0].country
     this.indexList.forEach(letter => {
       let value = []
       this.countyList.forEach((item, index) => {

         if(item.countryPinyin.charAt(0) == letter ){
           value.push(item)
         }
       })
       this.indexMap.set(letter,value)
     })
     this.countyLoading = false
    },
    //获取当前定位
    getNowPlace() {
      uni.getLocation({
        type: 'gcj02',
        success: function (res) {
          // console.log('获取定位111', res);
          // console.log('当前位置的经度：' + res.longitude);
          // console.log('当前位置的纬度：' + res.latitude);
        }
      });
      this.amapPlugin.getRegeo({
        success: (data) => {
          console.log('高德地图', data)
          //获取位置
          this.SignAddress = data[0].regeocodeData.addressComponent.province + ' . ' + data[0].regeocodeData.addressComponent.city;
          this.location.country = data[0].regeocodeData.addressComponent.country
          this.location.province = data[0].regeocodeData.addressComponent.province
          this.location.city = data[0].regeocodeData.addressComponent.city
          this.locationLoading = false
          // uni.showToast({
          //   title: '获取位置成功',
          //   duration: 2000,
          //   icon: 'none'
          // });
          // uni.hideLoading();
        },
        fail: function (err) {
          console.log('获取位置失败', err)
          uni.showToast({
            title: '获取位置失败',
            duration: 2000,
            icon: 'error'
          });
        }
      });
    },
//重新发起获取当前位置授权
    rGetLocation() {
      let _this = this
      uni.authorize({
        scope: 'scope.userLocation',
        success() { //1.1 允许授权
          _this.getNowPlace()
        },
        fail() { //1.2 拒绝授权
          uni.showModal({
            content: '检测到您没打开获取信息功能权限，是否去设置打开？',
            confirmText: "确认",
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({
                  success: (res) => {
                    console.log(res);
                    _this.getNowPlace()
                  }
                })
              } else {
                console.log('取消');
                return false;
              }
            }
          })
          return false;
        }
      })

    },


  },
}
</script>

<style lang="scss">
.list {

  &__item {
    @include flex;
    padding: 6px 12px;
    align-items: center;

    &__avatar {
      height: 35px;
      width: 35px;
      border-radius: 3px;
    }

    &__user-name {
      font-size: 16px;
      margin-left: 10px;
      color: $u-main-color;
    }
  }

  &__footer {
    color: $u-tips-color;
    font-size: 14px;
    text-align: center;
    margin: 15px 0;
  }
}
</style>
